'use strict';
const db = uniCloud.database();
const dbCmd = db.command
const $ = db.command.aggregate
const tools = require("../../tools/index.js")
const alioss = require('../../oss/index.js')
const noticeS = require('../notice/index.js')

// 发布文章
exports.PushArticle = async (body_data) => {
	let returnData = { code: 200,msg: "参数错误~" }
	let {_id,contents,imgList,videoList,audioList,PushType } = body_data
	
	if (!_id || !PushType) return returnData
	
	try{
		let addJson = {
			UserId: _id,
			contents,
			PublishTime: new Date(),
			imgList,
			videoList,
			audioList,
			PushType,
			likeList: [],
			shareList: [],
			viewCount: 0
		}
		
		if (!imgList) delete addJson.imgList
		if (!videoList) delete addJson.videoList
		if (!audioList) delete addJson.audioList
		
		// 添加文章数据（妈的用事务写 不能拿到id）
		let result = await db.collection('Article').add(addJson)
		if(!result.id) return {code:500,msg:"操作未成~"}
		
		let affair = await db.runTransaction(async transaction => {
			// 返回出去刚添加的那篇文章
			let SelNewDataOne = await transaction.collection('Article').aggregate().match({_id:result.id}).sort({
				PublishTime: -1
			}).limit(1).lookup({
				from: 'User',
				localField: 'UserId',
				foreignField: '_id',
				as: "UserInfo"
			}).lookup({
				from: 'common',
				localField: '_id',
				foreignField: 'articleId',
				as: "CommonList"
			}).end()
			
			// 返回该用户是否点赞过  _id是数据库的用户id
			if (SelNewDataOne.data.length > 0 && _id) {
				SelNewDataOne.data.forEach(i => {
					i.likeList.forEach(item => {
						if (item.UserId === _id) {
							i['iSlike'] = true
						}
					})
					i['likeCount'] = i.likeList.length  	// 外加点赞总数
				})
			}
			return {
				code: 200,
				msg: "发布成功~",
				data: SelNewDataOne.data[0]
			}
		})
		return affair
	}catch(e){
		console.log('内部错误~')
		returnData.code=500
		returnData.msg='内部错误'
		return returnData
	}

	
}

// 删除文章
exports.DelArticle = async (body_data)  =>{
	let returnData = { code: 200,msg: "参数错误~" }
	let {articleId} = body_data
	if(!articleId) return returnData
	
	try {
		const affair = await db.runTransaction(async transaction => {
			// 删除文章 +  删除媒体的数据 + 评论数据
			let SelRes = await transaction.collection('Article').doc(articleId).get()
			let DelRes = await transaction.collection('Article').doc(articleId).remove()			// 删除文章
			let DelCommonRes = await transaction.collection('common').where({articleId}).remove() 	// 删除评论信息
			let DelImgResult=null,DelAudioResult=null
			if(SelRes.data.imgList && SelRes.data.imgList.length>0){
				// 有图片的删除图片
				let fileList = []  // 删除文件的id数组
				SelRes.data.imgList.forEach((i)=>{fileList.push(i.fileid)})
				DelImgResult = await uniCloud.deleteFile({fileList});
			}else if(SelRes.data.audioList){
				// 有录音的删除录音
				let DelFileID = SelRes.data.audioList.fileID
				DelAudioResult = await alioss.deleteFile(DelFileID)									// 删除oss文件
				await transaction.collection('UploadRecord').where({fileID:DelFileID}).remove()		// 删除上传记录
			}
			return {	DelImgResult,DelAudioResult,DelRes,DelCommonRes	}
		})
		return {
			code:200,
			msg:"删除成功~",
			data:affair
		}
	} catch (e) {
		console.error('事务报错：', e)
		return {
			code: 500,
			msg: '内部错误~',
			error: e
		}
	}
}

// 获取文章列表
exports.SelArticleList = async (body_data) => {
	let returnData = { code: 200,msg: "参数错误~" }
	let {pageSize,pageNum,UserInfo} = body_data
	let Skips = pageNum * pageSize
	if (!pageSize) return returnData
	
	let total = await db.collection('Article').count() // 拿文章总数

	try {
		const affair = await db.runTransaction(async transaction => {
			// 返回文章列表信息
			let result = await transaction.collection('Article').aggregate().sort({
				PublishTime: -1
			}).skip(Skips).limit(pageSize).lookup({
				from: 'User',
				localField: 'UserId',
				foreignField: '_id',
				as: "UserInfo"
			}).lookup({
				from: 'common',
				localField: '_id',
				foreignField: 'articleId',
				as: "CommonList"
			}).end()

			// 返回该用户是否点赞过  _id是数据库的用户id
			if (result.data.length > 0 && UserInfo._id) {
				result.data.forEach(i => {
					i.likeList.forEach(item => {
						if (item.UserId === UserInfo._id) {
							i['iSlike'] = true
						}
					})
					i['likeCount'] = i.likeList.length
				})
			}
			return result
		})
		return {
			code: 200,
			msg: "查询成功~",
			data: affair.data,
			total: total.total
		}
	} catch (e) {
		console.error('事务报错：', e)
		return {
			code: 500,
			msg: '内部错误~',
			error: e
		}
	}
}

// 获取视频列表（未作）
exports.SelVideoList = async (body_data) => {
	let returnData = { code: 200,msg: "参数错误~" }
	let {
		pageSize,
		pageNum,
		UserId
	} = body_data
	let Skips = pageNum * pageSize
	if (!pageSize) return returnData

	try {
		const affair = await db.runTransaction(async transaction => {

			// 返回文章列表信息
			let result = await transaction.collection('Article').aggregate().match({
				PushType: "video/text"
			}).lookup({
				from: 'User',
				localField: 'UserId',
				foreignField: '_id',
				as: "UserInfo"
			}).lookup({
				from: 'common',
				localField: '_id',
				foreignField: 'articleId',
				as: "CommonList"
			}).sort({
				PublishTime: -1
			}).limit(pageSize).skip(Skips).end()

			// 查询评论总数
			// 过滤添加 iSlike字段
			if (result.data.length > 0 && UserId) {
				result.data.forEach(i => {
					i.likeList.forEach(item => {
						if (item.UserId === UserId) {
							i['iSlike'] = true
						}
					})
				})
			}
			return result
		})
		return {
			code: 200,
			msg: "查询成功~",
			data: affair.data
		}
	} catch (e) {
		console.error('事务报错：', e)
		return {
			code: 500,
			msg: '内部错误~',
			error: e
		}
	}
}

// 查询当前文章详细信息(这边好像是来加载评论/点赞/观看数的)
exports.SelArticleDetail = async (body_data) => {
	let returnData = { code: 200,msg: "参数错误~" }
	let {articleId,UserInfo} = body_data
	if (!articleId) return returnData
	
	try{
		let affair = await db.runTransaction(async transaction => {
			let result = await transaction.collection('Article').where({_id: articleId}).field({
				_id: true,
				likeList: true,
				viewCount: true
			}).get()
			
			// 返回该用户是否点赞过  _id是数据库的用户id
			if (result.data.length > 0 && UserInfo.UserId) {
				result.data.forEach(i => {
					i.likeList.forEach(item => {
						if (item.UserId === UserInfo.UserId) {
							i['iSlike'] = true
						}
					})
				})
			}
			// 获取评论总数
			let CommonTotal = await db.collection('common').where({articleId}).count()
			result.data[0].CommonTotal = CommonTotal.total
			return {
				code: 200,
				msg: "查询成功~",
				data: result.data[0]
			}
		})
		return affair
	}catch(e){
		console.error('事务报错：', e)
		return {
			code: 500,
			msg: '内部错误~',
			error: e
		}
	}
	
	
}

// 查询个人发布
exports.SelPersionPublish = async (body_data) => {
	let returnData = { code: 200,msg: "参数错误~" }
	let {
		pageSize,
		pageNum,
		UserId,
		PersionId
	} = body_data
	if (!pageSize || !PersionId) return returnData
	
	let Skips = pageNum * pageSize

	try {
		const affair = await db.runTransaction(async transaction => {
			let PublishTotal = await transaction.collection('Article').where({UserId:PersionId}).count()
			
			// 获取要查看那个人的个人信息
			let UserInfo = await transaction.collection('User').where({_id:PersionId}).field({
				Nickname:true,
				avatar:true
			}).get()
			
			// 返回文章列表信息
			let result = await transaction.collection('Article').aggregate().match({
				UserId: PersionId
			}).sort({
				PublishTime: -1
			}).skip(Skips).limit(pageSize).lookup({
				from: 'User',
				localField: 'UserId',
				foreignField: '_id',
				as: "UserInfo"
			}).lookup({
				from: 'common',
				localField: '_id',
				foreignField: 'articleId',
				as: "CommonList"
			}).end()

			// 返回该用户是否点赞过  _id是数据库的用户id
			if (result.data.length > 0 && UserId) {
				result.data.forEach(i => {
					i.likeList.forEach(item => {
						if (item.UserId === UserId) {
							i['iSlike'] = true
						}
					})
					i['likeCount'] = i.likeList.length
				})
			}
			
			return {
				code: 200,
				msg: "查询成功~",
				data:{
					UserInfo:UserInfo.data[0],
					ArticleList:result.data
				},
				total:PublishTotal.total
			}
		})
		return affair
	} catch (e) {
		console.error('事务报错：', e)
		return {
			code: 500,
			msg: '内部错误~',
			error: e
		}
	}
}

// 文章的模糊搜索
exports.SelArticle_like = async (body_data)=>{
	let returnData = { code: 200,msg: "参数错误~" }
	let {content,pageSize,pageNum} = body_data
	if(!content || !pageSize) return returnData
	
	try{
		
		let Skips = pageSize * pageNum
		// 模糊查询
		let like_Json = {}
		like_Json['contents'] = new RegExp(`${content}`)
		let res = await db.collection('Article').aggregate().match(like_Json).sort({PublishTime:-1}).limit(pageSize).skip(Skips)
		.lookup({
			from:'User',
			localField:'UserId',
			foreignField:'_id',
			as:"UserInfo"
		}).lookup({
			from:'common',
			localField:'_id',
			foreignField:'parentId',
			as:"SecondList"
		}).end()
		returnData.code=200
		returnData.msg='查询成功~'
		returnData.data = res.data
		return returnData
		
	}catch(e){
		returnData.code=500
		returnData.msg='内部错误~'
	}
	
	
}

// 上传文件记录(文章上传音频是放在oss上的，以后包括视频要放在oss上)
exports.UploadRecord = async(body_data)=>{
	let returnData = { code: 200,msg: "参数错误~" }
	let {fileID,UploadType,duration} = body_data
	if(!fileID || !UploadType) return returnData
	
	let addJson = {fileID,duration,fileUrl:'https://' + alioss.ossConfig.host + '/' + fileID}
	let res = await db.collection('UploadRecord').add(addJson)
	if(res.id){
		returnData.msg='上传，插入成功~'
		returnData.data = addJson
		return returnData
	}else{
		return {code:500,msg:"内部错误~"}
	}
}

// 点赞接口（点赞文章的）
exports.onLike = async (body_data) => {
	let returnData = { code: 200,msg: "参数错误~" }
	let {_id,UserInfo} = body_data
	if (!_id) return returnData
	
	
	try{
		const affair = await db.runTransaction(async transaction => {
			//  查询该用户是否点赞过
			let IsLike = await transaction.collection('Article').aggregate().match({_id}).project({
				UserId:1, 				// 将id传递到下个流水线
				likeList: $.filter({	// 将likeList传递到下个流水线
					input: '$likeList',  
					as: 'item',
					cond: $.eq(['$$item.UserId', UserInfo._id])  // 合并同一用户重复点赞
				})
			}).end()
			
			
			// 已点赞过 取消点赞
			if (IsLike.data[0].likeList.length > 0) {
				// return {code: 200,msg: "您已点赞过~",iSlike: true}
				const res = await transaction.collection('Article').where({_id}).get() // 取数据
				
				if(res.data.length>0){
					let index = res.data[0].likeList.findIndex((i)=>i.UserId===UserInfo._id) // 取likeList中该用户点赞信息的下标
					res.data[0].likeList.splice(index,1)	// 切割
					let result = await transaction.collection('Article').doc(_id).update({likeList: res.data[0].likeList}) // 刷新
					if(result.updated>0){
						return {
							code: 200,
							msg: "点赞取消成功~",
							iSlike: false
						}
					}else{
						return {code:204,msg:"更新未成功~"}
					}
				
				}else{
					return {code:204,msg:"请求超时1"}
				}
				
			 // 未点赞过
			} else {
				
				// 更新数据中的likeList插入数据
				let result = await transaction.collection('Article').doc(_id).update({
					likeList: dbCmd.push([{
						UserId:UserInfo._id,
						UpdateTime: Date.now(),
						Ip: __ctx__.CLIENTIP
					}])
				})
				
				
				// 添加通知信息
				let SelJson = {
					noticeUserId:IsLike.data[0].UserId,
					noticeArticleId:_id,
					noticeType:1,
					SourceUserId:UserInfo._id
				}
				let NoticeRes = await noticeS.addNotice(SelJson)
				
				
				return {
					code: 200,
					msg: "点赞成功~",
					iSlike: true,
					data: result,
					NoticeRes:NoticeRes
				}
			}
		})
		return affair
	}catch(e){
		console.error('事务报错：', e)
		return {
			code: 500,
			msg: '内部错误~',
			error: e
		}
	}
	
	
}
